//* Copyright(C) 2005-2012, all rights reserved.
//*
//* The following code is copyrighted and contains proprietary information
/* and trade secrets of Foxit Software Inc.      
 **************************************************************************
 */

/**
 * Bookmark插件类；
 * 需求的plugin: navigation panel;
 */
define(function (require, exports, module) {
    var PDFBookMark = require("./PDFBookmark");
    require("../../ImageEngine/PDFBookmarkLoader.js");
    /**
     * Bookmark UI node
     * @param parentNodeId id of parent node
     * @param curNodeId id of current node
     * @param {WebPDF.PDFData.PDFBookMark} pdfBookmark pdf bookmark object.
     * @constructor
     */
    function BookmarkNode(parentNodeId, curNodeId, pdfBookmark) {
        /**
         * Id of parent node
         * @type {Number}
         */
        this.parentNodeId = parentNodeId;
        /**
         * Id of current node
         * @type {Number}
         */
        this.curNodeId = curNodeId;
        /**
         * PDF bookmark node
         * @type {WebPDF.PDFData.PDFBookMark}
         */
        this.pdfBookmark = pdfBookmark;
        /**
         * bookmark node list.
         * @type {Array.<BookmarkNode>}
         */
        this.childNodeList = [];
        /**
         * Add child bookmark node .
         * @param {BookmarkNode} childNode child bookmark node .
         */
        this.addChildNode = function (childNode) {
            this.childNodeList.push(childNode);
        };
    }


    /**
     * Bookmark tree
     * @param readerApp app instance.
     * @constructor
     */
    var BookmarkTree = function (readerApp) {
        var _root = null;
        var _readerApp = readerApp;
        var extNodeClass = 'bookmarkNode', extPlusItemClass = 'bookmarkPlusItem';
        var baseUrl = readerApp.getBaseUrl() + "images/reader/dtree/";
        var icons  = {
            root: '',
            folder: baseUrl + 'bk.png',
            folderOpen: baseUrl + 'bk.png',
            node: baseUrl + 'bk.png',
            nodehot: baseUrl + 'bk1.png',
            empty: baseUrl + 'empty.png',
            line: baseUrl + 'line.png',
            join: baseUrl + 'join.png',
            joinBottom: baseUrl + 'joinbottom.png',
            joinTop: baseUrl + 'jointop.png',
            joinonly: baseUrl + 'joinonly.png',
            plus: baseUrl + 'plug.png',
            plusBottom: baseUrl + 'plugbottom.png',
            plusTop: baseUrl + 'plugtop.png',
            plusOnly: baseUrl + 'plugonly.png',
            minus: baseUrl + 'minus.png',
            minusBottom: baseUrl + 'minusbottom.png',
            minusTop: baseUrl + 'minustop.png',
            minusOnly: baseUrl + 'minusonly.png',
            nlPlus: baseUrl + 'nolines_plus.gif',
            nlMinus: baseUrl + 'nolines_minus.gif'
        };
        var _bookmarkTree = new WebPDFTools.dTree(_readerApp.getAppId() + '_bm_', extNodeClass, extPlusItemClass, icons);

        /**
         * Create bookmark tree.
         * @param {WebPDF.PDFData.PDFBookMark} pdfRootBookmark root of pdf bookmark
         */
        this.createTree = function (pdfRootBookmark) {
            _root = new BookmarkNode(-1, 0, pdfRootBookmark);
            _bookmarkTree.add(_root.curNodeId, _root.parentNodeId, "");
            _enumBookmark(_root, pdfRootBookmark);
        };
        /**
         * Get html string for bookmark tree.
         * @returns {String} html string for bookmark tree.
         */
        this.toHtmlString = function () {
            return _bookmarkTree.toString();
        };

        this.bindEvents = function (bookmarkViewerPanel) {
            var $mainFrame = $("#" + _readerApp.getMainView().getMainFrameID());
            $mainFrame.on('click', '.' + extNodeClass, function (event) {
                try {
                    var nodeId = parseInt(event.target.getAttribute("nodeid"));
                    var bookMarkNode = _getBookmarkNodeByID(_root, nodeId);
                    if (bookMarkNode) {
                        _bookmarkTree.setCurNode(nodeId);
                        _readerApp && _readerApp.getMainView().getDocView().goToPageByDestination(
                            bookMarkNode.pdfBookmark.getBookmarkInfo().destinationInfo);
                        return false;
                    }
                }
                catch (ex) {
                    console.error(ex);
                }
            });
            $mainFrame.on('click', '.' + extPlusItemClass, function (event) {
                try {
                    var nodeId = parseInt(event.target.getAttribute("nodeid"));
                    var bookMarkNode = _getBookmarkNodeByID(_root, nodeId);
                    if (bookMarkNode) {
                        _bookmarkTree.o(nodeId);
                        bookmarkViewerPanel.reinitializeScroll();
                        return false;
                    }
                }
                catch (ex) {
                    console.error(ex);
                }
            });
        };

        /**
         * Get bookmark node by id.
         * @param parentBookMarkNode parent bookmark node
         * @param nodeId node id
         * @returns {BookmarkNode}
         * @private
         */
        function _getBookmarkNodeByID(parentBookMarkNode, nodeId) {
            if (!parentBookMarkNode) {
                return null;
            }
            if (parentBookMarkNode.curNodeId === nodeId) {
                return parentBookMarkNode;
            }
            var childCount = parentBookMarkNode.childNodeList.length;
            for (var i = 0; i < childCount; i++) {
                var foundChildNode = _getBookmarkNodeByID(parentBookMarkNode.childNodeList[i], nodeId);
                if (foundChildNode) {
                    return foundChildNode;
                }
            }
            return null;
        }

        function _enumBookmark(parentNode, parentPDFBookmark) {
            var size = parentPDFBookmark.getChildCount();
            for (var k = 0; k < size; k++) {
                var childPDFBookmark = parentPDFBookmark.getChild(k);
                var childNode = _addBookmarkNode(parentNode, childPDFBookmark);
                _enumBookmark(childNode, childPDFBookmark);
            }
        }

        function _addBookmarkNode(parentNode, currentPDFBookmark) {
            var curBookmarkInfo = currentPDFBookmark.getBookmarkInfo();
            var bookmarkNode = new BookmarkNode(parentNode.curNodeId, curBookmarkInfo.currentIndex, currentPDFBookmark);
            parentNode.addChildNode(bookmarkNode);
            var bmkTitle = WebPDF.Common.htmlEncodeEx(curBookmarkInfo.title);
            _bookmarkTree.add(bookmarkNode.curNodeId, bookmarkNode.parentNodeId, bmkTitle);
            return bookmarkNode;
        }
    };


    WebPDF.BookmarkPluginName = "Bookmark Plugin";
    /**
     * Bookmark plugin
     * @param {WebPDF.ReaderApp} readerApp app instance
     * @extends {WebPDF.IReaderPlugin}
     * @constructor
     */
    WebPDF.BookmarkPlugin = function (readerApp) {
        var _readerApp = readerApp,
        //bookmark
            _bookmarkRootNode = null,
            _bookmarkTree = null,
            _scrollApi = null,
        //是否已经取完数据;
            _isBookmarkDataInitialized = false,
            _jqPanel = null,
            _jsonBookmarkData = null,
            _self = this;

        //private members
        function _init(jsonBookmarkData) {
            _jqPanel = $('#' + _self.getPanelID());
            if(!jsonBookmarkData)  {
                console.warn("Bookmark data is null.");
                return;
            }
            _jsonBookmarkData = jsonBookmarkData;
            _bookmarkRootNode = new PDFBookMark(null);
            _bookmarkRootNode.parserBookmarksInfo(jsonBookmarkData);
            _bookmarkTree = new BookmarkTree(_readerApp);
            _bookmarkTree.createTree(_bookmarkRootNode);
            _createHtml();
            _initScroll();
            _self.reinitializeScroll();
            _isBookmarkDataInitialized = true;
        }

        function _createHtml() {
            $("#" + _self.getPanelID()).append(_bookmarkTree.toHtmlString());
            _bookmarkTree.bindEvents(_self);
        }

        /**
         * Init touch events.
         * @private
         */
        function _initTouchEvent() {
            var oldX = 0;
            var oldY = 0;
            var endX = 0, endY = 0;
            var bMovePage = false;
            _jqPanel.off('touchstart touchmove touchend').on(
                'touchstart',
                function (e) {
                    if (e.originalEvent.touches != null && e.originalEvent.touches.length != 1)
                        return;
                    var touch = e.originalEvent.touches[0];
                    var elem = touch.target;
                    if(WebPDF.Common.isElemInteractive(elem)){
                        return true;
                    }
                    bMovePage = true;
                    oldX = touch.pageX;
                    oldY = touch.pageY;
                }
            ).on(
                'touchmove',
                function (e) {
                    if (e.originalEvent.touches != null && e.originalEvent.touches.length != 1)
                        return;
                    var touch = e.originalEvent.touches[0];
                    var elem = touch.target;
                    if(WebPDF.Common.isElemInteractive(elem)){
                        return true;
                    }
                    endX = touch.pageX;
                    endY = touch.pageY;
                    if (!bMovePage) {
                        return;
                    }
                    e.preventDefault();
                    _scrollApi.scrollBy(oldX - endX, oldY - endY);
                }
            ).on(
                'touchend',
                function () {
                    bMovePage = false;
                }
            );
        }

        function _initScroll() {
            if (_scrollApi != null){
                return;
            }
            var settings = {showArrows: false, animateScroll: false};
            var scrollApiElem = '';
            switch(_readerApp.getOptions().scrollBarType) {
                case WebPDF.PDFView.ScrollBarType.CUSTOM_SCROLL_BAR:
                {
                    scrollApiElem = _jqPanel.fwrJScrollPane(settings);
                }break;
                case WebPDF.PDFView.ScrollBarType.NATIVE_SCROLL_BAR:
                {
                    scrollApiElem = _jqPanel.WebPDFNativeScroll(settings);
                    if (WebPDF.Environment.mobile) {
                        _initTouchEvent();
                    }
                }break;
                default: {
                    $.error("Unsupported type of scroll bar.");
                }break;
            }
            _scrollApi = scrollApiElem.data('jsp');
            return _scrollApi;
        }

        //下面实现 INavigationChildPanel接口;
        this.getPanelID = function () {
            return _readerApp.getAppId() + "_fxBookmarkPanel";
        };
        this.getTabBtnID = function () {
            return _readerApp.getAppId() + "_bmtab";
        };
        this.getTabNorClass = function () {
            return "fwr-bookmark-panel-icon";
        };
        this.getTabHotClass = function () {
            return "fwr-bookmark-hot-panel-icon";
        };
        this.getTitle = function () {
            return "BookMark.Title";
        };
        this.onSize = function (panelWidth, panelHeight) {
            _jqPanel = $('#' + _self.getPanelID());
            if (!_jqPanel[0]) return;
            _jqPanel.css({ width: panelWidth, height: panelHeight });
            if (_isBookmarkDataInitialized) {
                if (!_scrollApi) {
                    _initScroll();
                }
                else {
                    _scrollApi.reinitialise();
                }
            }
        };
        //end INavigationChildPanel接口;

        this.reinitializeScroll = function () {
            _scrollApi && _scrollApi.reinitialise();
        };

        //获取Plugin名称;
        this.getPluginName = function () {
            return WebPDF.BookmarkPluginName;
        };
        //插件被注册的时候调用;
        this.onRegister = function () {
        };
        //模块初始化;
        this.init = function () {
            var pdfBookmarkLoader = new WebPDF.ImageEngine.PDFBookmarkLoader();
            pdfBookmarkLoader.asyncLoadPDFBookmark(_readerApp,_readerApp.getPDFDoc(), _init,$.noop);
        };
        //模块卸载;
        this.unload = function () {
        };

        /**
         * Get bookmark data in JSON format.
         * @returns {*}
         */
        this.getBookmarkData = function(){
           return _jsonBookmarkData;
        };
    };

    exports.createPlugin = function (readerApp) {
        return new WebPDF.BookmarkPlugin(readerApp);
    };
});